<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" :inline="true" label-width="68px">
      <el-form-item label="广告位名称" prop="advName">
        <el-input
          v-model="queryParams.advName"
          placeholder="请输入广告位名称"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="轮播位置" prop="type">
        <el-select
          v-model="queryParams.type"
          placeholder="请输入轮播位置"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        >
          <el-option
            v-for="item in options1"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>
    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary" icon="el-icon-plus" size="mini" @click="handleAdd">新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
        >删除</el-button>
      </el-col>
    </el-row>

    <el-table v-loading="loading" :data="ehAdvList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column prop="id" header-align="center" align="center" label="编号"></el-table-column>
      <el-table-column prop="pic" header-align="center" align="center" label="图片名称">
        <template slot-scope="scope">
          <img style="width:100px; height:100px" :src="scope.row.pic" />
        </template>
      </el-table-column>
      <el-table-column prop="advName" header-align="center" align="center" label="广告位名称"></el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button size="mini" type="text" icon="el-icon-edit" @click="handleUpdate(scope.row)">修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />
    <!-- 添加或修改对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="700px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-row>
          <el-col :span="24">
            <el-form-item label="标题" prop="advName">
              <el-input v-model="form.advName" placeholder="请输入" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="轮播位置" prop="type">
              <el-select
                v-model="form.type"
                placeholder="请输入轮播位置"
                clearable
                size="small"
                @keyup.enter.native="handleQuery"
              >
                <el-option
                  v-for="item in options1"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item label="图片" prop="pic">
          <el-upload
            class="avatar-uploader"
            name="files"
            :data="userData"
            :action="commitimg"
            :show-file-list="false"
            :on-success="handleAvatarSuccess"
            :before-upload="beforeAvatarUpload"
          >
            <div slot="tip" class="el-upload__tip">只能上传jpg/png文件，且不超过2M</div>
            <img v-if="imageUrl" :src="imageUrl" class="avatar" />
            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
          </el-upload>
        </el-form-item>
        <el-form-item label="备注" prop="note">
          <el-input v-model="form.note" placeholder="请输入备注" type="textarea" rows="4" />
        </el-form-item>
        <el-row>
          <el-col :span="2">
            <el-form-item prop="gridId">
              <el-input type="hidden" v-model="form.gridId" />
            </el-form-item>
          </el-col>
          <el-col :span="2">
            <el-form-item label prop="id">
              <el-input type="hidden" v-model="form.id" />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>
<script>
import {
  listEhAdv,
  getEhAdv,
  delEhAdv,
  addEhAdv,
  updateEhAdv
} from "@/api/portal/adv/ehadv";
import Cookies from "js-cookie";
export default {
  name: "EhAdv",
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      txt: "",
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 总条数
      total: 0,
      // 岗位表格数据
      ehAdvList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 图片
      imageUrl: "",
      //图片上传
      commitimg: process.env.VUE_APP_BASE_API + "/minio/api/minio/file/upload",
      //图片上传 额外添加数据
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        advName: undefined,
        type: undefined
      },
      options1: [
        {
          value: 0,
          label: "积分商城首页轮播"
        },
        {
          value: 1,
          label: "党群议事首页轮播"
        }
      ],
      optIndex: 0,
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        advName: [{ required: true, message: "不能为空", trigger: "blur" }],
        type: [
          {
            required: true,
            message: "轮播位置不能为空",
            trigger: "blur"
          }
        ],
        pic: [{ required: true, message: "不能为空", trigger: "blur" }],
        note: [{ required: true, message: "备注不能为空", trigger: "blur" }]
      }
    };
  },
  created() {
    this.getList();
  },
  methods: {
    /** 查询首页轮播广告表列表 */
    getList() {
      this.loading = true;
      listEhAdv(this.queryParams).then(response => {
        this.ehAdvList = response.data.list;
        this.total = response.data.total;
        this.loading = false;
      });
    },
    // 岗位状态字典翻译
    statusFormat(row, column) {
      return this.selectDictLabel(this.statusOptions, row.status);
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.imageUrl = "";
      this.form = {
        advName: undefined,
        type: undefined,
        pic: undefined,
        note: undefined
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    // 单个文件上传成功时
    handleAvatarSuccess(res, file) {
      this.imageUrl = URL.createObjectURL(file.raw);
      this.form.pic = res.imgArr[0];
      console.log("图片上传", this.form.pic);
    },
    beforeAvatarUpload(file) {
      const isJPG = file.type === "image/jpeg";
      const isPNG = file.type === "image/png";
      const isLt2M = file.size / 1024 / 1024 < 2;

      if (!isJPG && !isPNG) {
        this.$message.error("上传图片只能上传jpg/png文件!");
      }
      if (!isLt2M) {
        this.$message.error("上传头像图片大小不能超过 2MB!");
      }
      return (isJPG || isPNG) && isLt2M;
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id);
      this.single = selection.length != 1;
      this.multiple = !selection.length;
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加广告";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids;
      getEhAdv(id).then(response => {
        this.form = response.data;
        this.imageUrl = this.form.pic;
        this.open = true;
        this.title = "修改广告";
      });
    },
    /** 提交按钮 */
    submitForm: function() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          this.form.gridId = Cookies.get("ehuGridId");
          if (this.form.id != undefined) {
            updateEhAdv(this.form).then(response => {
              if (response.code === 200) {
                this.msgSuccess("修改成功");
                this.open = false;
                this.getList();
              } else {
                this.msgError(response.msg);
              }
            });
          } else {
            addEhAdv(this.form).then(response => {
              if (response.code === 200) {
                this.msgSuccess("新增成功");
                this.open = false;
                this.getList();
              } else {
                this.msgError(response.msg);
              }
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const idList = row.id || this.ids;
      this.$confirm(
        '是否确认删除广告位编号为"' + idList + '"的数据项?',
        "警告",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }
      )
        .then(function() {
          return delEhAdv(idList);
        })
        .then(() => {
          this.getList();
          this.msgSuccess("删除成功");
        })
        .catch(function() {});
    }
  }
};
</script>
<style>
.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.avatar-uploader .el-upload:hover {
  border-color: #409eff;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 100px;
  height: 100px;
  line-height: 100px;
  text-align: center;
}
.avatar {
  width: 100px;
  height: 100px;
  display: block;
}
.el-textarea .el-textarea__inner {
  resize: none;
}
</style>